package com.htfyun.factorytest.factorytestui;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.htfyun.factorytest.R;
import com.htfyun.factorytest.SimStateReceiver;
import com.htfyun.factorytest.common.PermissionManager;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.executor.AppExecutors;
import com.htfyun.factorytest.utils.mod.EasySimMod;

import java.util.Objects;

public class FactorySimCardActivity extends FactoryBaseActivity {
    private TextView mTxtTips;
    private TextView mTxtSimCardInfo;
    private TextView mSignalStrengthInfo;
    private TextView txtSimCardResult;
    private MobilePhoneStateListener listener;
    private SimStateBroadcastReceiver simStateReceiver;

    private EasySimMod easySimMod;

    private SignalStrength mSignalStrength;

    private static final int MSG_SIM_CARD_PASS = 100;
    private static final int MSG_DATA_ENABLED = 101;

    private String simState = "UNKNOWN";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener = new MobilePhoneStateListener();

        easySimMod = new EasySimMod(this);
        simStateReceiver = new SimStateBroadcastReceiver();

        if (!easySimMod.getTelephonyManager().isDataEnabled()) {
            easySimMod.getTelephonyManager().setDataEnabled(true);
        } else {
            easySimMod.getTelephonyManager().setDataEnabled(false);
            getHandler().sendEmptyMessageDelayed(MSG_DATA_ENABLED, 1000);
        }
        registerPhoneStateListener();
        registerSimStateReceiver();

        txtSimCardResult.setText(getSpannableString(getString(R.string.sim_card_test_info, "WAIT")));

    }

    @Override
    int getLayoutId() {
        return R.layout.activity_factory_sim_card;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

        mTxtTips = findViewById(R.id.txtTips);
        mTxtSimCardInfo = findViewById(R.id.txtSimCardInfo);
        mSignalStrengthInfo = findViewById(R.id.txtSignalStrengthInfo);
        txtSimCardResult = findViewById(R.id.txtSimCardResult);

        mTxtTips.setText(getString(R.string.sim_card_test_tips2));
    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {
        switch (msg.what) {
            case MSG_SIM_CARD_PASS:
                finishWithOK();
                break;
            case MSG_DATA_ENABLED:
                easySimMod.getTelephonyManager().setDataEnabled(true);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterPhoneStateListener();
        unregisterSimStateReceiver();
    }

    private void registerSimStateReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SimStateReceiver.ACTION_SIM_STATE_CHANGED);//(Intent.ACTION_SIM_STATE_CHANGED);
        registerReceiver(simStateReceiver, filter);
    }

    private void unregisterSimStateReceiver() {
        unregisterReceiver(simStateReceiver);
    }

    public void registerPhoneStateListener() {
        easySimMod.getTelephonyManager().listen(listener,
//                PhoneStateListener.LISTEN_SERVICE_STATE
//                        | 0x00800000/*PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED*/
                PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
//                        | PhoneStateListener.LISTEN_CALL_STATE
//                        | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
//                        | PhoneStateListener.LISTEN_DATA_ACTIVITY
//                        | PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE
//                        | PhoneStateListener.LISTEN_DISPLAY_INFO_CHANGED
        );
    }

    /**
     * Stop listening for phone direction changes.
     */
    public void unregisterPhoneStateListener() {
        easySimMod.getTelephonyManager().listen(listener, PhoneStateListener.LISTEN_NONE);
    }

    @SuppressLint("MissingPermission")
    private void updateSIMInfo() {
        StringBuilder sb = new StringBuilder();

        sb.append("SIM 卡基本信息:    ").append("\n");
        sb.append("SIM state:    ").append(simState).append("\n");
        sb.append("SIM state isReady:    ").append(easySimMod.getTelephonyManager().getSimState() == TelephonyManager.SIM_STATE_READY).append("\n");
        sb.append("IMSI:    ").append(easySimMod.getIMSI()).append("\n");
        sb.append("IMEI:    ").append(easySimMod.getIMEI()).append("\n");
        sb.append("Country: ").append(easySimMod.getCountry()).append("\n");
        sb.append("Number of active SIM:    ").append(easySimMod.getNumberOfActiveSim()).append("\n");
        sb.append("Phone Number:    ").append(easySimMod.getPhoneNumber()).append("\n");

        mTxtSimCardInfo.setText(sb.toString());

    }

    private int countForSignalStrengthOK = 0;
    private void updateSignalStrength() {
        String signalStrengthInfo = getString(R.string.signalStrength_test_info, mSignalStrength != null ? mSignalStrength.getLevel() : -1);

        mSignalStrengthInfo.setText(signalStrengthInfo);

        updateSIMInfo();

        if (mSignalStrength == null) {
            return;
        }
        int simState = easySimMod.getTelephonyManager().getSimState();

        if (mSignalStrength.getLevel() >= 3
                && simState == TelephonyManager.SIM_STATE_READY
                && ++countForSignalStrengthOK >= 3) {
            //PASS
            if (getBtnFail() != null) {
                getBtnFail().setEnabled(false);
            }
            getHandler().sendEmptyMessageDelayed(MSG_SIM_CARD_PASS, 2000);
            txtSimCardResult.setText(getSpannableString(getString(R.string.sim_card_test_info, "PASS")));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private class SimStateBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            DebugLog.d("action = " + action);
            if (Objects.equals(action, SimStateReceiver.ACTION_SIM_STATE_CHANGED)) {
                simState = intent.getStringExtra("ss");//Intent.EXTRA_SIM_STATE);
                DebugLog.d("simState = " + simState);
                AppExecutors.postToMainThread(FactorySimCardActivity.this::updateSIMInfo);
            }
        }
    }

    private class MobilePhoneStateListener extends PhoneStateListener {
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            DebugLog.d("onSignalStrengthsChanged level is " + signalStrength.getLevel() + ", simState = " + easySimMod.getTelephonyManager().getSimState());

            mSignalStrength = signalStrength;
            AppExecutors.postToMainThread(FactorySimCardActivity.this::updateSignalStrength);
        }
    }

    @NonNull
    private SpannableString getSpannableString(String infoString) {
        final SpannableString msp = new SpannableString(infoString);
        String resultSearch = getString(R.string.ft_use_result_for_search);
        String pass = getString(R.string.test_result_pass);
        int index = infoString.indexOf(resultSearch);
        if (index > 0) {
            int len = index + resultSearch.length() + pass.length();
            if (len > infoString.length()) {
                len = infoString.length();
            }
            msp.setSpan(new RelativeSizeSpan(1.6f), index, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), index, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            msp.setSpan(new UnderlineSpan(), index, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return msp;
    }

}
